package cn.yuhao.party.user.servlet;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.user.domain.User;
import cn.yuhao.party.user.service.UserService;

public class UserServlet extends BaseServlet {

private UserService userService = new UserService();
public String level(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	String username=request.getParameter("gusername");
	String level=request.getParameter("level");
	int lev=Integer.parseInt(level);
	userService.level(username,lev);
	request.setAttribute("msg", "级别管理操作成功");
	return "f:/adminjsps/msg.jsp";
}

public String findAll(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	int pc=getPc(request);
	String url=getUrl(request);
	PageBean<User> pb= (PageBean<User>) userService.findAll(pc);
	pb.setUrl(url);
	request.setAttribute("pb", pb);
	System.out.println(pb.getBeanList());
	return "f:/adminjsps/roles.jsp";
}
	
	public String quit(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		return "r:/jsps/login/index.jsp";
	}
	
	public String login(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User formUser=CommonUtils.toBean(request.getParameterMap(), User.class);
		
		User user=userService.login(formUser);
		/*
		 * 校验功能未写
		 */
		if(user==null){
			request.setAttribute("msg", "用户名或密码不正确");
			request.setAttribute("user", user);
			return "f:/jsps/login/msg.jsp";
		}else{
			request.getSession().setAttribute("sessionUser", user);
			String loginname=user.getGusername();
			loginname=URLEncoder.encode(loginname);
			Cookie cookie=new Cookie("loginname", loginname);
			cookie.setMaxAge(1000*60*24*7);
			response.addCookie(cookie);
			return "r:/jsps/login/welcome/index.jsp";
		}
		
	}
	private int getPc(HttpServletRequest req) {
		int pc = 1;
		String param = req.getParameter("pc");
		if(param != null && !param.trim().isEmpty()) {
			try {
				pc = Integer.parseInt(param);
			} catch(RuntimeException e) {}
		}
		return pc;
	}
	
	
	private String getUrl(HttpServletRequest req) {
		String url = req.getRequestURI() + "?" + req.getQueryString();
		
		int index = url.lastIndexOf("&pc=");
		if(index != -1) {
			url = url.substring(0, index);
		}
		return url;
	}
	
}
